<?php
class Pageley_Domain_Validator_Unique extends Pageley_Domain_Validator_Required {
	private $gateway;
	private $notUniqueMessage = "error.validation.notUnique";
	
	public function validate($value, $propertyName, $object) {
		if($this->gateway === null) {
		    $this->gateway = Pageley_Config::getInstance()->valueOf("gateway");
		}
	    
	    $errors = parent::validate($value, $propertyName, $object);
		if($errors->size() === 0) {
		    $record = $this->gateway->findByProperty($object->getType(), $propertyName, $value);
			$notUnique = $this->rejectIfTrue($record !== null && $record->getId() !== $object->getId(), 
			    $this->notUniqueMessage, array("{field." . $propertyName . "}", $value));
			if($notUnique) {
				$errors->put($propertyName, $notUnique);
			}
		}
		return $errors;
	}
	
	public function setGateway($gateway) {
		$this->gateway = $gateway;
	}
	
	public function setNotUniqueMessage($notUniqueMessage) {
		$this->notUniqueMessage = $notUniqueMessage;
	}
}